<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Logout.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\user;

use app\api\model\dao\Picture;
use app\api\model\dao\TaskLog;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserCurrency;
use app\api\model\data\currency\ConsumeCurrency;
use app\library\Common;
use think\Exception;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use think\Log;
use app\library\aliyun\oss\OssWorker;
use app\library\aliyun\sts\StsWorker;
use app\library\Flag;


class Update extends PageBase
{

    private $objUserAccount;
    private $objOss;
    private $objPicture;
    private $objTaskLog;
    private $objUserCurrency;


    public function __construct()
    {
        parent::__construct();

        $this->objUserAccount = new UserAccount();
        $this->objOss = new OssWorker();
        $this->objPicture = new Picture();
        $this->objTaskLog = new TaskLog();
        $this->objUserCurrency = new ConsumeCurrency();

    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'user_id' => 'require',
        ];
        $msg = [
            'user_id.require' => '账号ID必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        $file = request()->file('file');

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            Log::alert(__METHOD__ . ' param: ' . json_encode($param));
            return $this->getRes(Error::ERR_PARAM);
        }

        // 如上传的是头像
        if (!empty($_FILES["file"])) {
            $file = $_FILES["file"];

            // 错误判断
            if ($file['error'] > 0) {
                switch ($file['error']) {
                    case 1:
                        $this->errno = Error::ERR_FILE_LARGER_THAN_SERVER;
                        break;
                    case 2:
                        $this->errno = Error::ERR_FILE_LARGER;
                        break;
                    case 3:
                        $this->errno = Error::ERR_FILE_UNCOMPLETE;
                        break;
                    case 4:
                        $this->errno = Error::ERR_FILE_LOAD;
                        break;
                    default:
                        $this->errno = Error::ERR_PARAM;
                        break;
                }
                return $this->getRes($this->errno);
            }

            // 大小判断
            if ($file['size'] > (Flag::IMGMAXWIDTH * Flag::IMGMAXHIGHT)) {
                Log::error(__METHOD__ . " uploadimage is too large.filetsize:{$file['size']}.arrInput:" . json_encode($param));
                return $this->getRes(Error::ERR_FILE_TOO_LARGE);
            }

            // 类型判断
            $tp = array("image/jpg", "image/gif", "image/jpeg", "image/png", "image/pjpeg");
            if (!in_array($file["type"], $tp)) {
                Log::error(__METHOD__ . " uploadimage filetype failed.filetype:{$file['type']}.arrInput:" . json_encode($param));
                return $this->getRes(Error::ERR_FILE_TYPE_ERROR);
            }

            // 文件md5是否正确，MD5校验先关了
            $md5file = md5_file($file['tmp_name']);
//        if($md5file != $param['md5']) {
//            throw new Exception('check file MD5 fail...');
//        }

            $ret = explode('.', $file['name']);
            $suffix = end($ret);
            $object_name = "$md5file.$suffix";//文件名
            $file_name = $file['tmp_name'];

            $date = date('Ymd');

            $username = Flag::$map_pic[Flag::CONST_PICTURE_PEOPLE] . '/' . $date;

            // 上传文件
            $file_url = $this->objOss->uploadFile($username, $object_name, $file_name);
            if (false === $ret) {
                return $this->getRes(Error::ERR_FILE_UPLOAD_FAIL);
            }

            // 添加到DB中记录上传图片
            $input = [
                'userid' => $param['user_id'],
                'type' => Flag::CONST_PICTURE_PEOPLE,
                'obj_id' => 0,
                'url' => $file_url,
                'create_time' => time(),
            ];
            $this->objPicture->addPicture($input);

            $param['avatar'] = $file_url;

        }

        $ret = $this->objUserAccount->updateUserAccount($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }

        $ret = $this->task($param['user_id']);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }

        return $this->getRes();
    }

    /**
     * 完善个人资料看是否完成任务
     *
     * @param $userid
     * @return bool
     */
    public function task($userid)
    {

        $date = date('Ymd');

        $arrCond = [
            'task_id' => ['=', 2],
            'userid' => $userid,
        ];
        $ret = $this->objTaskLog->getTaskLog($arrCond);
        if (false === $ret) {
            Log::error(__METHOD__ . ' get task log fail.[cond:' . json_encode($arrCond) . ']');
            return false;
        }
        if (empty($ret)) {
            $user_account = $this->objUserAccount->getUserAccountByUserids([$userid]);
            if (false === $user_account) {
                Log::error(__METHOD__ . ' get user account fail.[userid:' . $userid . ']');
                return false;
            }
            $user_account = $user_account[0];
            unset($user_account['id']);
            $account_finish_cnt = 0;
            $account_total_cnt = count($user_account);
            foreach ($user_account as $val) {
                if ($val) {
                    $account_finish_cnt++;
                }
            }
            if ($account_finish_cnt == $account_total_cnt) {
                $arrInput = [
                    'task_id' => 1,
                    'userid' => $userid,
                    'date' => $date,
                ];
                $ret = $this->objTaskLog->addTaskLog($arrInput);
                if (false === $ret) {
                    Log::error(__METHOD__ . ' add task log fail.[param:' . json_encode($arrInput) . ']');
                    return false;
                }
                Common::addIntegral($userid, 'task_account');
            }
        }
    }
}
